<template>
  <div class="llt-table flex1">
    <div class="aic jcb llt-table-right " :class="border ? 'llt-table-header' : ''">
      <div class="llt-table-left aic flex1 flexWrap">
        <slot name="tableHeader"> </slot>
      </div>
      <div class="llt-table-right aic">
        <div class="" @click="handleDrawerBool">
          <el-icon class="llt-icon-size-21 mx15">
            <setting />
          </el-icon>
        </div>
      </div>
    </div>
    <div class="tableContent">
      <div style="margin-bottom: 10px;">
        <filterView :filterTabs="state.filters" @handleDeleteTag="handleDeleteTag" @handleCloseAll="handleCloseAll">
        </filterView>
      </div>
      <slot name="tableContent">
        <!-- v-loading="state.loading" -->
        <el-table ref="tableRef" :data="state.tableData" v-on="_tableEvents" v-bind="tableAttrs">
          <!-- 多选 -->
          <el-table-column v-if="selection" type="selection" :reserve-selection="reserveSelection" width="40" />
          <el-table-column v-if="showIndex" type="index" label="序号" width="60" />
          <template v-for="(item, index) in columnsSelf" :key="index">
            <TableColumn v-if="item.visible===undefined ||item.visible===true" :item="item">
           
            <!-- <template #[`${item.prop}`]="scope">
              <slot :name="item.prop"     :row="scope.row"
         :column="scope.item"> 
              </slot>
              
            </template> -->
                <template v-for="(_, slotName) in $slots"
                 v-slot:[slotName]="slotProps">
          <slot :name="slotName" v-bind="slotProps"></slot>
        </template>

            </TableColumn>
          </template>
       
          <!-- 操作 -->
          <slot name="operation">
            <TableColumn :item="operation" v-if="operation" />
          </slot>
          <!-- 插入表格最后一行之后的插槽 -->
          <template #append>
            <slot name="append"> </slot>
          </template>

          <!-- 表格无数据情况 -->
          <template #empty>
            <div class="table-empty">
              <slot name="empty">
                <el-result title="抱歉，当前暂无数据。" sub-title="">
                  <template #icon>
                    <img style="width: 150px" :src="baseUrl+'icon/emptyData.svg'" alt="" />
                  </template>
                </el-result>
              </slot>
            </div>
          </template>
        </el-table>
      </slot>
    </div>
    <div v-if="pagination.total">
      <el-pagination class="paginationBox" v-model="pagination.currentPage" :page-size="pagination.pageSize"
        :layout="pagination.layout" :page-sizes="pagination.pageSizes" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
      
    </div>
  </div>
  <columnSetting :columns="columnsSelf" @handelColumns="handelColumns" ref="columnSettingRef"></columnSetting>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  onMounted,
  onUpdated,
  nextTick,
  PropType,
  computed,
  watch,
  unref,
  toRaw,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "./Column";

import filterView from "/@/components/Filter/filterView.vue";
import columnSetting from "/@/components/table/component/columnSetting.vue";
// import { type } from "os";
import { ElMessage } from "element-plus";
import { FilterValueFormat, getFormData, resetFilter } from "./hook";
import formatTool from "/@ts/hooks/format";
const { handleTree } = formatTool();
const baseUrl = import.meta.env.VITE_BASE
const router = useRouter();
const emit = defineEmits([
  "getCurrentColumns",
  "size-change",
  "current-change",
  "selection-change",
  "result",
  "getParmas"
]);
const pullData = () => {
  if (!props.data) {
    getList();
  } else {
    getParmas()
  }
}
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1;
  pullData();
};
const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page;
  pullData();
};
const route = useRoute();
const _seamlessRolling =() =>{
  if (props.seamlessRolling) {
    let tableDom = tableRef.value.$el
  let elTableBody  = tableDom.querySelectorAll(".el-table__body")[0]
  elTableBody.style.animation =`listScroll ${props.animationTime}s linear infinite`;
    }
 

}
 

const props: any = defineProps({
  operation: {
    //列数据
    type: Object,
    default: null,
  },
  tableEvents: {
    type: Object,
    default: () => {
      return {};
    },
  },
  filter: {
    //列数据
    type: Object,
    default: () => {
      return {
      };
    },
  },
  tableOptions: {
    //列数据
    type: Object,
    default: () => {
      return {
      };
    },
  },
  columns: {
    //列数据
    type: Array,
    default: () => [],
  },
  threeOption: {
    //是否是树形表格
    type: Object,
    default: () => {
      return null
    },
  },
//是否展示序号
  showIndex: {
        type: Boolean,
    default: false,
  },  
  animationTime: {
    type: Number,
    default: 10,
  },
  //是否无缝滚动
  seamlessRolling: {
    type: Boolean,
    default: false,
  },
  loading: {
    //高度是否撑满   true
    type: Boolean,
    default: true,
  },
  isInit: {
    //是否初始化数据   true
    type: Boolean,
    default: true,
  },
  dataKey: {
    //   true
    type: String,
    default: "rows",
  },
  //单选数据还是多选数据 默认false 单选数据
  selectTypeMultiple: {
    type: Boolean,
    default: true,
  },
  // 点击选择当前行
  clickSelectRow: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  // 是否多选
  selection: {
    type: Boolean as PropType<boolean>,
    default: true,
  },
  // 仅对 type=selection 的列有效，类型为 Boolean，为 true 则会在数据更新之后保留之前选中的数据（需指定 row-key）
  reserveSelection: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  pageInfo: {
    //列数据
    type: Object,
    default: () => {
      return {
        currentPage: 1,

        pageSize: 100,
        pageSizes: [100, 200, 300, 400],
        layout: "total, prev, pager, next,sizes",
        total: 0,
      }
    },
  },
  apiFunction: {
    //列数据
    type: Function,
    default: () => { },
  },
  data: {
    type: Array,
    default: null,
  },
});
const _tableEvents = computed(() => {
  return Object.assign({
    "selection-change": handleselectionChangeRow,
    "row-click": handleRowClick
  }, props.tableEvents)
})

const tableAttrs = computed(() => {
  return Object.assign({
  }, props.tableOptions)
})

const pagination = computed(() => {
  return toRaw(props.pageInfo);
});

const columnsSelf = ref<TableColumn[]>([]);
watch(
  () => props.columns,
  (val) => {
    if(val&&val.length>0){
      //处理列表逻辑 添加是否有高级筛选
       columnsSelf.value = val.map((item:any)=>{
        let params = {
          renderHeader:null
        };
        if(item.filter){
          params.renderHeader = ({column}:any) => {
            return (      <filterBox
              title={column.label}
              valueKey={column.property}
             {...item.filter}
              onChange={handleFilterBox}
              onSort={handleOrder}
              data={state.formFilter}
            ></filterBox>)
          }
        }
        return {
          ...item,
          ...params
        }
        });
    }

  },
  { deep: true, immediate: true },
);
const state: any = reactive({
  tableData: [],
  filters: [], //筛选展示数据
  screenModeDataObj: {}, //筛选查询数据
  loading: true,
  formFilter: {},
});
const _selectRow = () => {

}
const handleRowClick = (row) => {
  if(props.clickSelectRow){
    tableRef.value.toggleRowSelection(row, true)
  }
 
}
const handleDeleteTag = (indexValue: any, index: any) => {
  state.screenModeDataObj = {};
  //删除指定标签数据 并且
  state.filters[index].value.splice(indexValue, 1);
  //获取当前操作的值
  let currentKeyData = state.filters[index];

  if (currentKeyData.value == 0) {
    //删除这个字段
    state.filters.splice(index, 1);
  }
  //同步数据  formFilter
  state.formFilter[currentKeyData.key].splice(indexValue, 1);
  // 获取列表请求参数
  if (Object.keys(FilterValueFormat(state.filters)).length == 0) {
    state.screenModeDataObj = {};
  } else {
    Object.assign(state.screenModeDataObj, FilterValueFormat(state.filters));
  }
  pagination.value.currentPage = 1;
  pullData()
};
const handleCloseAll = (indexValue: any, index: any) => {
  resetFilter(state.formFilter);

  state.filters = [];
  state.screenModeDataObj = {};
  pagination.value.currentPage = 1;
  pullData()
};
const paramsALL = ref({})
const getParmas = () => {
  const pageData = unref(pagination);
  const data = {
    pageNum: pageData.currentPage,
    pageSize: pageData.pageSize,
    ...state.screenModeDataObj,
    ...props.filter
  }
  paramsALL.value = data;
  emit("getParmas", data)

}
const handleOrder = ({ data, valueKey, title }: any) => {
  if (data&&data.order) {
    state.screenModeDataObj["isAsc"] = data.order;
    state.screenModeDataObj["orderByColumn"] = valueKey;
  } else {
    state.screenModeDataObj["isAsc"] = "";
    state.screenModeDataObj["orderByColumn"] = "";
  }
  pagination.value.currentPage = 1;
  pullData()
};

const handleFilterBox = ({ data, valueKey, title, type }: any) => {
  if (data.length > 0) {
    //处理数据
    state.formFilter[valueKey] = data;
    state.filters = getFormData({
      data,
      key: valueKey,
      title,
      type,
      filters: state.filters,
    });
    // 获取列表请求参数
    Object.assign(state.screenModeDataObj, FilterValueFormat(state.filters));
  } else {
    delete state.screenModeDataObj[valueKey];
    delete state.formFilter[valueKey];

    let delIndex = -1;
    state.filters.forEach((item: any, index: any) => {
      if (item.key == valueKey) {
        delIndex = index;
      }
    });
    if (delIndex != -1) {
      state.filters.splice(delIndex, 1);
    }
  }
  pagination.value.currentPage = 1;
  pullData()

};
/**
 * 处理复选框
 * @param selection 选中的数据
 */

// 用于存储当前选中的行数据
const selectedRow = ref(null);
const handleselectionChangeRow = (selections: any) => {
  if (props.selectTypeMultiple) {
    emit("selection-change", toRaw(selections));
  } else {
    if (selections.length > 1) {
      // 只保留最后一次选择的行
      for (let index = 0; index < selections.length - 1; index++) {
        const element = selections[index];
        tableRef.value.toggleRowSelection(element, false);
      }
    }

  }
  if (props.selectTypeMultiple) {
    emit("selection-change", toRaw(selections));
  } else {
    if (selections.length == 1) {
      emit("selection-change", toRaw(selections[0]));
    }

  }

};
/*
 * 触发列表请求
 */

const getList = (queryParams?: any) => {
  state.tableData = []
  if (typeof props.apiFunction === "function") {
    getParmas();
    const listApi = props.apiFunction;
    state.loading = true;

    if (queryParams && queryParams.pageNum) {
      pagination.value.currentPage = queryParams.pageNum;
    }
    listApi({
      ...paramsALL.value,
      ...queryParams,
    })
      .then((result: ResponseConfig) => {
        const data: any = result;
        const list = data[props.dataKey];
        
        pagination.value.total = result.total ? result.total : 0;
        state.loading = false;
        if (props.threeOption) {
          state.tableData = handleTree(list, props.threeOption.id, props.threeOption.parentId);
        } else {
          state.tableData = list
        }
        //动画
         _seamlessRolling()
        emit("result", result);
      })
      .catch((err: any) => { });
  } else {
    ElMessage.warning("请设置apiFunction");
  }
};
watch(
  () => props.data,
  (val) => {

    if (val) {
      state.tableData = val;
      state.loading = false;
      nextTick(() => {
        _seamlessRolling()
       })
    } else {
      if (props.isInit && typeof props.apiFunction === "function") {
        getList();
      }
    }
  },
  {
    deep: true,
    immediate: true,
  },
);
 
/**
 * 设置列表弹框
 */
const columnSettingRef = ref();
const handleDrawerBool = () => {
  columnSettingRef.value.open();
};
/**
 * 更新列表字段
 */
const tableRef = ref();
const handelColumns = (columns: TableColumn[]) => {
  columnsSelf.value = columns;

  tableRef.value.doLayout();
};
const getTableRef = () => {
  return tableRef.value
}
defineExpose({
  getList,
  handleOrder,
  handleFilterBox,
  tableRef: getTableRef,
  paramsALL,
  getParmas,
  formFilter: state.formFilter,
});
</script>

<style lang="scss">
@keyframes listScroll {
  from {
    transform: translateY(0%); /* 初始位置，从顶部开始 */
  }
  to {
    transform: translateY(-100%); /* 滚动到最底部，这里假设列表高度刚好是容器高度的整数倍，实际应用可能需要根据具体情况调整这个值 */
  }
}
.seamlessRolling{
}
.llt-table {
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100%;
z-index: 2;
  .el-table {
    flex: 1;
  }

  .tableContent {
    display: flex;
    flex: 1;
    flex-direction: column;
    overflow: auto;
  }

  .paginationBox {
    margin-top: 10px;
  }
}

.llt-table-header {
  border-top: 1px solid #eee;
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
